<template>
  <div style="padding: 20px">
    <view class="hor-layout">
      <el-upload class="upload" :limit="1" :show-file-list="false"
                 action="" :multiple="false" :on-change="importExcel"
                 accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
        <el-button size="mini" type="primary">上传Excel</el-button>
      </el-upload>
      <el-button type="danger" size="mini" style="margin-left: 20px" :loading="addLoading" :disabled="!canAddUse"
                 @click="addBatchClick">批量上传
      </el-button>
    </view>
    <el-table :data="tableData" border height="70vh" style="margin-top: 10px;">
      <el-table-column type="index" label="#" show-overflow-tooltip align="center"/>
      <el-table-column v-for="(value,key) in keyMap" :prop="value" :label="key"
                       align="center" show-overflow-tooltip/>
    </el-table>
  </div>
</template>

<script>
import XLSX from 'xlsx'
import { getHouseInfo } from "@/common/common.js"

export default {
  data() {
    return {
      keyMap: {
        "楼房号": "build_house_num",
        "楼栋号": "build_num",
        "单元号": "unit_num",
        "房号": "house_num",
        "姓名": "username",
        "手机号": "phone",
      },
      addLoading: false,
      tableData: []
    }
  },
  computed: {
    canAddUse() {
      return this.tableData.length > 0
    }
  },
  methods: {
    addBatchClick() {
      let list = this.tableData.map(item => {
        let {build_num, unit_num, house_num, username, phone} = item
        return {build_num, unit_num, house_num, username, phone: phone.toString()}
      })
      console.log("addBatchClick", list)
      this.addLoading = true
      this.$confirm("确认批量上传房号？", '确认信息').then(res => {
        this.$db.collection('plot-house').add(list).then(res => {
          this.$message.success("上传成功！")
          uni.navigateBack({delta: 1})
        }).catch(err => this.$message.error(err.message))
            .finally(() => this.addLoading = false)
      })
    },
    convertTable(data) {
      data.forEach(item => {
        for (const key in item) {
          let newKey = this.keyMap[key]
          if (newKey) item[newKey] = item[key], delete item[key]
        }
        //如果楼房号存在，将楼房号分解为楼号、单元号、房号
        if (item.build_house_num) {
          let {build_num, unit_num, house_num} = getHouseInfo(item.build_house_num)
          item.build_num = build_num
          item.unit_num = unit_num
          item.house_num = house_num
        }
      })
      this.tableData = data
      this.$emit("tableData", data)
    },
    // 导入表格
    importExcel(param) {
      this.file2Xce(param).then(item => {
        if (item && item.length > 0) {
          if (item[0] && item[0].sheet && item[0].sheet.length) {
            let tableData = item[0].sheet  //把数据塞到表格预览
            this.convertTable(tableData)
          }
        }
      }).catch(error => {
        console.error(error)
      });
    },
    /**
     *解析文件
     */
    file2Xce(file) {
      return new Promise(function (resolve, reject) {
        const reader = new FileReader();
        reader.onload = function (e) {
          const data = e.target.result;
          this.wb = XLSX.read(data, {
            type: "binary"
          });
          const result = [];
          this.wb.SheetNames.forEach(sheetName => {
            result.push({
              sheetName: sheetName,
              sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName])
            });
          });
          resolve(result);
        };
        reader.readAsBinaryString(file.raw);
      });
    }
  }
}
</script>

<style scoped>
</style>
